<template>
  <div class="canvas-container">
    <!-- 画布 -->
    <canvas ref="canvas"></canvas>

    <!-- 控件按钮 -->
    <div class="controls">
      <input type="file" multiple @change="uploadImage" accept="image/*" />
      <button @click="addText">添加文字</button>
      <button @click="addArrow">添加箭头</button>
      <button @click="saveCanvas">保存数据</button>
      <button @click="loadCanvas">加载数据</button>
      <button @click="clearCanvas">清空画布</button>
      <!-- 新增删除选中元素按钮 -->
      <button @click="deleteSelectedElement">删除选中元素</button>
      <button @click="saveAsImage">保存为图片</button>
    </div>
    <!-- 加载提示 -->
    <div v-if="isLoading" class="loading">加载中...</div>
    <!-- 显示保存的图片 -->
    <div v-if="savedImageUrl" class="saved-image">
      <img :src="savedImageUrl" alt="Saved Canvas Image">
    </div>
  </div>
</template>

<script>
import { fabric } from "fabric";

export default {
  data() {
    return {
      canvas: null, // 画布实例
      savedData: null, // 存储的画布数据
      isLoading: false, // 加载状态
      savedImageUrl: null, // 图片路径
    };
  },
  mounted() {
    // 初始化 Fabric 画布
    this.canvas = new fabric.Canvas(this.$refs.canvas, {
      width: 800,
      height: 500,
      backgroundColor: "#f8f8f8"
    });
  },
  methods: {
    /** 上传图片到画布 */
    uploadImage(event) {
      if (!event || !event.target || !event.target.files) {
        console.error("文件上传错误，event 未定义");
        return;
      }
      const files = event.target.files;
      for (let file of files) {
        if (!this.isValidImageFile(file)) {
          console.error(`不支持的文件类型: ${file.name}`);
          continue;
        }
        const reader = new FileReader();
        reader.onload = (e) => {
          if (fabric && fabric.Image) {
            fabric.Image.fromURL(e.target.result, (img) => {
              img.set({
                left: 100,
                top: 100,
                scaleX: 0.5,
                scaleY: 0.5,
                selectable: true
              });
              this.canvas.add(img);
            });
          } else {
            console.error("fabric.Image 未正确加载");
          }
        };
        reader.readAsDataURL(file);
      }
    },
    /** 检查文件是否为有效的图片类型 */
    isValidImageFile(file) {
      const validTypes = ["image/jpeg", "image/png", "image/gif"];
      return validTypes.includes(file.type);
    },
    /** 添加文字 */
    addText() {
      const text = new fabric.IText("输入文字", {
        left: 150,
        top: 150,
        fontSize: 20,
        fill: "black",
        selectable: true
      });
      this.canvas.add(text);
    },
    /** 添加箭头 */
    addArrow() {
      const line = new fabric.Line([50, 100, 200, 100], {
        stroke: "red",
        strokeWidth: 5,
        selectable: true
      });
      const triangle = new fabric.Triangle({
        left: 205,
        top: 92,
        width: 20,
        height: 25,
        fill: "red",
        angle: 90
      });
      // 组合箭头
      const arrow = new fabric.Group([line, triangle], {
        left: 100,
        top: 100,
        selectable: true
      });
      this.canvas.add(arrow);
    },
    /** 保存画布数据 */
    saveCanvas() {
      try {
        this.savedData = JSON.stringify(this.canvas.toJSON());
        localStorage.setItem("fabricCanvas", this.savedData);
        alert("画布已保存！");
      } catch (error) {
        console.error("保存画布数据时出错:", error);
        alert("保存失败，请稍后重试。");
      }
    },
    /** 加载画布数据 */
    async loadCanvas() {
      const data = localStorage.getItem("fabricCanvas");
      if (data) {
        try {
          this.isLoading = true;
          await new Promise((resolve) => {
            this.canvas.loadFromJSON(data, () => {
              this.canvas.renderAll();
              resolve();
            });
          });
          alert("画布数据加载成功！");
        } catch (error) {
          console.error("加载画布数据时出错:", error);
          alert("加载失败，请检查数据是否损坏。");
        } finally {
          this.isLoading = false;
        }
      } else {
        alert("没有保存的数据！");
      }
    },
    /** 清空画布 */
    clearCanvas() {
      this.canvas.clear();
      this.canvas.setBackgroundColor("#f8f8f8", this.canvas.renderAll.bind(this.canvas));
    },
    /** 删除选中元素 */
    deleteSelectedElement() {
      const activeObject = this.canvas.getActiveObject();
      if (activeObject) {
        this.canvas.remove(activeObject);
        this.canvas.discardActiveObject().renderAll();
      } else {
        alert("请先选择要删除的元素。");
      }
    },
    /** 保存画布为图片 */
    saveAsImage() {
      this.savedImageUrl = this.canvas.toDataURL({
        format: "png", // 可以选择 "jpeg" 或 "png"
        quality: 1.0 // 图片质量
      });
     
      // // 创建一个临时链接元素进行下载
      // const link = document.createElement("a");
      // link.href = dataURL;
      // link.download = "canvas_image.png"; // 文件名
      // link.click(); // 触发下载
    }
  }
};
</script>

<style scoped>
.canvas-container {
  text-align: center;
  margin-top: 20px;
  position: relative;
}

canvas {
  border: 1px solid #ddd;
}

.controls {
  margin-top: 10px;
}

button {
  margin: 5px;
  padding: 8px 12px;
  cursor: pointer;
}

.loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
}
</style>